'use client'
import React, {useEffect, useState} from "react";
import {
    Card,
    Code,
    Spinner,
    AccordionItem,
    Avatar,
    Link,
    Navbar,
    NavbarBrand,
    NavbarContent,
    NavbarItem, Chip, Switch, ScrollShadow
} from "@nextui-org/react";
import ViewShare from "@/app/service/view/ViewShare";
import ViewNote from "@/app/service/view/ViewNote";
import {decodeFromBase64, encodeToBase64} from "next/dist/build/webpack/loaders/utils";
import {MdCatalog, MdPreview} from "md-editor-rt";
import 'md-editor-rt/lib/style.css';
import {useParams} from "react-router-dom";
import {useRouter} from "next/router";
import {search} from "@codemirror/search";
import {CardBody} from "@nextui-org/card";
import {PiClockClockwiseBold} from "react-icons/pi";
import {MoonIcon, SunIcon} from "@nextui-org/shared-icons";
import {Divider} from "@nextui-org/divider";
import {ScrollOverflowCheck} from "@nextui-org/use-data-scroll-overflow";
import {px} from "framer-motion";

export default function ViewSharePage(shareInfo: { s_id: string }) {
    //路径参数获取
    /*const [searchParams, setSearchParams] = useSearchParams();*/
    //状态定义
    /*const location = useLocation();*/
    //分享Id临存
    //const [shareId, setShareId] = useState<any>(null/*searchParams.get("shareId")*/);
    //加载中状态
    const [isLoading, setIsLoading] = useState(true);
    //执行状态
    const [isSuccess, setIsSuccess] = useState({
        state: false,
        message: '正在获取中...🎯',
        data: {
            icon: '',
            updateTime: '',
            content: '',
            title: ''
        }
    });

    const [light, setLight] = useState(true);
    /**
     * 通过参数方式---获取shareId  ***?shareId=?
     * */
    /*useEffect(() => {
        // 检查是否在客户端运行
        if (typeof window !== 'undefined') {
            //状态定义
            const search = window.location.search;
            const params = new URLSearchParams(search);//使用 URLSearchParams 解析查询字符串
            const shareIdParam = params.get('shareId');//获取shareId
            if (shareIdParam !== '' && shareIdParam !== null) {
                setShareId(shareIdParam);
            }
        }
    }, [])*/
    /**
     * 同年路由获取ShareId  ***\shareId\*
     */
    const shareId = shareInfo.s_id;

    /*获取分享数据*/
    async function initData() {

        if (!shareId) {
            //ToastUtil('必要的数据不能为空哦 😭', '❎', "error");
            setIsSuccess({
                state: false,
                message: '必要的数据不能为空哦 😭',
                data: {
                    icon: '',
                    updateTime: '',
                    content: '',
                    title: ''
                }
            });
            return;
        }


        const responseShare = await ViewShare(shareId);/*获取笔记ID*/
        if (responseShare.status) {
            const responseNote = await ViewNote(responseShare.data.noteId);/*获取笔记内容*/
            if (responseNote.status) {
                setIsSuccess({state: true, message: responseNote.message, data: responseNote.data});
            } else {
                //ToastUtil(responseNote.message, '❎', "error");
                setIsSuccess({
                    state: false,
                    message: responseNote.message, data: {
                        icon: '',
                        updateTime: '',
                        content: '',
                        title: ''
                    }
                });
                return;
            }
        } else {
            //ToastUtil(responseShare.message, '❎', "error");
            setIsSuccess({
                state: false, message: responseShare.message, data: {
                    icon: '',
                    updateTime: '',
                    content: '',
                    title: ''
                }
            });
            return;
        }
    }

    /*再通过检测shareId变化去加载数据，渲染前加载(钩子是在客户端执行)*/
    useEffect(() => {
        //判断是否空再加载数据
        if (shareId !== null && shareId !== undefined && shareId !== '') {
            setIsLoading(true);
            initData().then(() => {
                setIsLoading(false);
            });
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [shareId/*location*/]);
    return (
        <div className={light ? 'light' : 'dark'}>
            {
                isLoading ?
                    /*加载中*/
                    <div className={'flex justify-center h-screen items-center bg-white'}>
                        <Card className={'flex flex-col h-screen w-screen'} shadow={"md"} radius={'lg'}>
                            <CardBody>
                                <div className={'flex justify-center flex-grow items-center bg-white p-5'}>
                                    <Spinner label="加载ing...😵‍💫" color="primary" labelColor="primary"
                                             size={"sm"}/>
                                </div>
                            </CardBody>
                        </Card>
                    </div> : !isSuccess.state ?
                        /*请求存在问题*/
                        DontShare(isSuccess.message) :
                        <>
                            <div
                                className={`
                                w-full h-[48px]
                                border-b-1
                                border-b-gray-300
                                dark:border-b-gray-800
                                shadow-inner
                                ps-3.5 pe-3.5 flex 
                                items-center 
                                overscroll-x-auto 
                                overflow-x-auto 
                                whitespace-nowrap 
                                scrollbar-hide 
                                backdrop-filter 
                                backdrop-blur-lg 
                                fixed z-[1000]`}>
                                <p className="font-bold text-inherit">{isSuccess.data?.icon}</p>
                                <Divider orientation={'vertical'} className={`h-5 w-[0.3px] ms-2 me-1`}/>
                                <p className={`font-bold text-inherit ps-1 pe-1 ${light ? 'text-black' : 'text-white'}`}>{isSuccess.data?.title}</p>
                                <Divider orientation={'vertical'} className={`h-5 w-[0.3px] ms-1 me-2`}/>
                                <Chip
                                    startContent={<PiClockClockwiseBold size={18}/>}
                                    variant="flat"
                                    size={'sm'}
                                    color="secondary"
                                >
                                    {isSuccess.data?.updateTime}
                                </Chip>
                                <div className={`ps-2 w-screen flex justify-end items-end`}>
                                    <Switch
                                        defaultSelected
                                        size="sm"
                                        color="secondary"
                                        isSelected={light}
                                        onValueChange={setLight}
                                        thumbIcon={({isSelected, className}) =>
                                            isSelected ? (
                                                <SunIcon className={className}/>
                                            ) : (
                                                <MoonIcon className={className}/>
                                            )
                                        }
                                    />
                                </div>
                            </div>
                            {/*<Navbar className={`absolute backdrop-filter backdrop-blur-sm`} height={"48px"}
                                    maxWidth={"full"}
                                    isBlurred={true}
                                    isBordered={true}
                                    position={'sticky'}
                            >
                                <NavbarBrand>
                                </NavbarBrand>
                            </Navbar>*/}
                            {/*渲染笔记数据*/}
                            <div className={'flex justify-center h-screen items-center bg-white'}>
                                <Card className={'flex flex-col h-screen w-screen'}
                                      shadow={"md"} radius={'none'}>
                                    <CardBody>
                                        {/*内容*/}
                                        <MdPreview className={`dark:bg-transparent`}
                                                   modelValue={decodeFromBase64(isSuccess.data.content)}
                                                   previewTheme={'default'}
                                                   showCodeRowNumber
                                                   theme={light ? 'light' : 'dark'}/>
                                    </CardBody>
                                </Card>
                            </div>
                        </>
            }
        </div>
    )

    /*不存在的分享*/
    function DontShare(message: string) {
        return (
            <div className={'flex justify-center h-screen items-center bg-white'}>
                <Card className={'flex flex-col h-screen w-screen'} shadow={"md"} radius={'lg'}>
                    <CardBody>
                        <div className={'flex justify-center flex-grow items-center bg-white p-5'}>
                            <Code color="warning"> {message} </Code>
                        </div>
                    </CardBody>
                </Card>
            </div>
        )
    }
}